package com.shop.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.shop.base.BaseController;
import com.shop.result.ResultVO;
import com.shop.service.OrderService;
import com.shop.util.AlipayUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付控制器
 *
 * @author ZJL
 * @date 2025/6/3
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/alipay")
public class AlipayController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);

    private final AlipayUtils alipayUtils;
    private final OrderService orderService;

    @Value("${frontend.url:http://localhost:5173/#/pages/order/settlement}")
    private String frontendUrl;

    /**
     * 发起支付宝支付
     *
     * @param orderId     订单编号
     * @param orderAmount 订单金额
     * @param orderName   订单名称
     * @return 支付表单或二维码
     */
    @GetMapping("/pay")
    public ResultVO<String> alipay(
            @RequestParam("orderId") String orderId,
            @RequestParam("orderAmount") Float orderAmount,
            @RequestParam("orderName") String orderName) {
        logger.info("发起支付宝支付，订单编号: {}, 金额: {}, 名称: {}", orderId, orderAmount, orderName);

        // 手动验证参数
        if (orderId == null || orderId.trim().isEmpty()) {
            logger.warn("订单编号为空");
            return error("订单编号不能为空");
        }
        if (orderAmount == null || orderAmount <= 0) {
            logger.warn("订单金额无效，金额: {}", orderAmount);
            return error("订单金额必须大于0");
        }
        if (orderName == null || orderName.trim().isEmpty()) {
            logger.warn("订单名称为空");
            return error("订单名称不能为空");
        }

        try {
            // 验证订单是否存在且未支付
            if (!orderService.isValidOrder(orderId)) {
                logger.warn("订单无效或已支付，订单编号: {}", orderId);
                return error("订单无效或已支付");
            }
            String result = alipayUtils.sendRequestToAlipay(orderId, orderAmount, orderName);
            logger.info("支付请求成功发送，订单号: {}", orderId);
            return success(result);
        } catch (AlipayApiException e) {
            logger.error("支付宝API调用异常，订单编号: {}，错误信息: {}", orderId, e.getMessage(), e);
            return error("支付请求失败: " + e.getErrMsg());
        } catch (Exception e) {
            logger.error("支付请求处理异常，订单编号: {}", orderId, e);
            return error("支付处理发生系统错误，请稍后重试");
        }
    }

    /**
     * 支付宝同步回调
     */
    @GetMapping("/toSuccess")
    public void payReturn(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("支付宝同步回调开始");
        String outTradeNo = request.getParameter("out_trade_no");
        String totalAmount = request.getParameter("total_amount");

        if (outTradeNo == null || outTradeNo.trim().isEmpty() || totalAmount == null || totalAmount.trim().isEmpty()) {
            logger.warn("同步回调参数缺失，out_trade_no: {}, total_amount: {}", outTradeNo, totalAmount);
            response.sendRedirect(frontendUrl + "?error=invalid_params");
            return;
        }

        logger.info("同步回调，订单编号: {}, 金额: {}", outTradeNo, totalAmount);
        String redirectUrl = String.format("%s?orderId=%s", frontendUrl, outTradeNo);
        response.sendRedirect(redirectUrl);
    }

    /**
     * 支付宝异步回调
     */
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) {
        logger.info("接收到支付宝异步通知");
        try {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeStatus = params.get("trade_status");
            String outTradeNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String totalAmount = params.get("total_amount");

            logger.info("订单号: {}, 支付宝交易号: {}, 交易状态: {}, 金额: {}", 
                      outTradeNo, tradeNo, tradeStatus, totalAmount);

            if (!"TRADE_SUCCESS".equals(tradeStatus)) {
                logger.warn("异步回调支付状态非成功，订单编号: {}, 状态: {}", outTradeNo, tradeStatus);
                return "fail";
            }

            // 签名验证
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayUtils.alipayPublicKey, "UTF-8");
            if (!checkSignature) {
                logger.error("异步回调签名验证失败，订单编号: {}", outTradeNo);
                return "fail";
            }

            // 防止重复处理
            if (orderService.isOrderPaid(outTradeNo)) {
                logger.info("订单已支付，忽略重复回调，订单编号: {}", outTradeNo);
                return "success";
            }

            // 更新订单状态
            try {
                orderService.updateOrderStatus(outTradeNo, tradeNo, totalAmount);
                logger.info("订单支付状态更新成功，订单编号: {}", outTradeNo);
                return "success";
            } catch (Exception e) {
                logger.error("订单状态更新失败，订单编号: {}", outTradeNo, e);
                return "fail";
            }
        } catch (Exception e) {
            logger.error("异步通知处理失败", e);
            return "fail";
        }
    }
}